using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
    private static bool _applicationIsQuitting = false;
    private static readonly object _lock = new object();

    public static T Instance
    {
        get
        {
            if (_applicationIsQuitting) return null;
            lock (_lock)
            {
                _instance = FindObjectOfType<T>();
                if (_instance == null)
                {
                    GameObject singletomObj = new GameObject(typeof(T).Name);
                    _instance = singletomObj.AddComponent<T>();
                    DontDestroyOnLoad(singletomObj);
                }
            }
            return _instance;
        }
    }

    public virtual void Awake()
    {
        if (_instance == null)
        {
            _instance = this as T;
            DontDestroyOnLoad(gameObject);
        }
        else if (_instance != this)
        {
            Destroy(gameObject); 
        }
    }
    private void OnDestroy()
    {
        _applicationIsQuitting = true ;       
    }
}
